package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.product.api.domain.Product;
import com.spzx.product.api.domain.ProductDetails;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.product.api.domain.vo.SkuQuery;
import com.spzx.product.api.domain.vo.SkuStockVo;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 商品Service业务层处理
 */
@Slf4j
@Service
@Transactional
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private ProductDetailsMapper productDetailsMapper;

    @Autowired
    private SkuStockMapper skuStockMapper;

    //@Autowired
    //private StringRedisTemplate stringRedisTemplate; //适合 key和value都是字符串类型

    @Autowired
    private RedisTemplate redisTemplate; //适合值是任意类型

    /**
     * 查询商品列表
     *
     * @param product 商品
     * @return 商品
     */
    @Override
    public List<Product> selectProductList(Product product) {
        return productMapper.selectProductList(product);
    }

    //原子性
    @Override
    public int insertProduct(Product product) {
        //1.保存Product对象到product表
        productMapper.insert(product); //主键回填

        //2.保存List<ProductSku>对象到product_sku表
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (CollectionUtils.isEmpty(productSkuList)) {
            throw new ServiceException("SKU数据为空");
        }
        int size = productSkuList.size();
        for (int i = 0; i < size; i++) {
            ProductSku productSku = productSkuList.get(i);
            productSku.setSkuCode(product.getId() + "_" + i);
            productSku.setSkuName(product.getName() + " " + productSku.getSkuSpec());
            productSku.setProductId(product.getId());
            productSkuMapper.insert(productSku);

            //添加商品库存  //3.保存List<SkuStock>对象到sku_stock表
            SkuStock skuStock = new SkuStock();
            skuStock.setSkuId(productSku.getId());
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setLockNum(0);
            skuStock.setAvailableNum(productSku.getStockNum());
            skuStock.setSaleNum(0);
            skuStockMapper.insert(skuStock);
        }

        //4.保存ProductDetails对象到product_details表
        ProductDetails productDetails = new ProductDetails();
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetails.setProductId(product.getId());
        productDetailsMapper.insert(productDetails);

        return 1;
    }


    @Override
    public Product selectProductById(Long id) {
        //1.根据id查询Product对象
        Product product = productMapper.selectById(id);

        //2.封装扩展字段：查询商品对应多个List<ProductSku>
        //select * from product_sku where product_id =?
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
        List<Long> productSkuIdList = productSkuList.stream().map(productSku -> productSku.getId()).toList();


        // select * from sku_stock where sku_id in (1,2,3,4,5,6)
        List<SkuStock> skuStockList = skuStockMapper.selectList(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, productSkuIdList));

        Map<Long, Integer> skuIdToTatalNumMap = skuStockList.stream().collect(Collectors.toMap(SkuStock::getSkuId, SkuStock::getTotalNum));
        productSkuList.forEach(productSku -> {
            //返回ProductSku对象，携带了库存数据；
            productSku.setStockNum(skuIdToTatalNumMap.get(productSku.getId()));
        });

        product.setProductSkuList(productSkuList);

        //3.封装扩展字段：商品详情图片List<String>
        ProductDetails productDetails = productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
        String imageUrls = productDetails.getImageUrls();   //url,url,url
        String[] urls = imageUrls.split(",");
        product.setDetailsImageUrlList(Arrays.asList(urls));
        //返回Product对象
        return product;
    }


    @Override
    public int updateProduct(Product product) {
        //1.更新Product
        productMapper.updateById(product);

        //2.更新SKU   List<ProductSku>
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (CollectionUtils.isEmpty(productSkuList)) {
            throw new ServiceException("SKU数据为空");
        }
        productSkuList.forEach(productSku -> {
            productSkuMapper.updateById(productSku);

            //3.更新库存   List<ProductSku> -> 获取扩展字段stockNum
            SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, productSku.getId()));
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setAvailableNum(skuStock.getTotalNum() - skuStock.getLockNum());
            skuStockMapper.updateById(skuStock);
        });

        //4.更新详情ProductDetails
        ProductDetails productDetails = productDetailsMapper
                .selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, product.getId()));
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetailsMapper.updateById(productDetails);

        return 1;
    }


    @Override
    public int deleteProductByIds(Long[] ids) {
        //1.删除Product表数据
        // delete from product where id in (1,2)
        productMapper.deleteBatchIds(Arrays.asList(ids));

        //2.删除ProductSku表数据
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId, Arrays.asList(ids)));
        List<Long> productSkuIdList = productSkuList.stream().map(ProductSku::getId).toList();
        productSkuMapper.deleteBatchIds(productSkuIdList);

        //3.删除SkuStock表数据
        skuStockMapper.delete(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, productSkuIdList));

        //4.删除ProductDetails表数据
        // delete from product_details where product_id in (1,2)
        productDetailsMapper.delete(new LambdaQueryWrapper<ProductDetails>().in(ProductDetails::getProductId, Arrays.asList(ids)));
        return 1;
    }


    @Override
    public void updateAuditStatus(Long id, Integer auditStatus) {
        Product product = new Product();
        product.setId(id);
        if (auditStatus == 1) {
            product.setAuditStatus(1);
            product.setAuditMessage("审批通过");
        } else {
            product.setAuditStatus(-1);
            product.setAuditMessage("审批拒绝");
        }
        productMapper.updateById(product);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        Product product = new Product();
        product.setId(id);
        if (status == 1) {
            product.setStatus(1);
            productMapper.updateById(product);

            ProductSku productSku = new ProductSku();
            productSku.setStatus(1);
            productSkuMapper.update(productSku, new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));


            String key = "sku:product:data";
            List<ProductSku> productSkuList = productSkuMapper
                    .selectList(new LambdaQueryWrapper<ProductSku>()
                            .eq(ProductSku::getProductId, id));
            productSkuList.forEach(item -> {
                redisTemplate.opsForValue().setBit(key, item.getId(), true);
            });

        } else {
            product.setStatus(-1);
            productMapper.updateById(product);

            ProductSku productSku = new ProductSku();
            productSku.setStatus(-1);
            productSkuMapper.update(productSku, new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));

            String key = "sku:product:data";
            List<ProductSku> productSkuList = productSkuMapper
                    .selectList(new LambdaQueryWrapper<ProductSku>()
                            .eq(ProductSku::getProductId, id));
            productSkuList.forEach(item -> {
                redisTemplate.opsForValue().setBit(key, item.getId(), false);
            });
        }

    }


    @Override
    public List<ProductSku> getTopSale() {
        return productSkuMapper.getTopSale();
    }


    @Override
    public List<ProductSku> skuList(SkuQuery skuQuery) {
        return productSkuMapper.skuList(skuQuery);
    }


    /**
     * 服务提供者：6个接口来服务于商品详情查询。需要进行优化，提供查询效率。
     * 需要使用redis来提高性能。
     */

    @Override
    public ProductSku getProductSku(Long skuId) {
        try {
            //1.从redis缓存中获取数据,有直接返回
            //缓存数据的key名称定义
            String dataKey = "product:sku:" + skuId;
            ProductSku productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);
            if (redisTemplate.hasKey(dataKey)) { //缓存数据存在直接返回
                log.info("命中缓存，直接返回，线程ID：{}，线程名称：{}", Thread.currentThread().getId(), Thread.currentThread().getName());
                return productSku;
            }

            //2.redis缓存中没有，获取分布式锁
            String lockKey = "product:sku:lock:" + skuId;
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(lockKey, uuid, 5, TimeUnit.SECONDS);

            if (ifAbsent) {
                try {
                    //2.1 获取分布式锁成功
                    productSku = this.getSkuFromDB(skuId);

                    //将数据库获取的数据存储到缓存中，给下次访问利用缓存，提高效率。
                    //解决换成穿透问题， 方案1：数据库里没有数据，也要缓存null数据。只能解决同一个key的缓存穿透问题。
                    int ttl = productSku == null ? 60 : 600;   //null值缓存1分钟，非null值缓存10分钟。
                    redisTemplate.opsForValue().set(dataKey, productSku, ttl, TimeUnit.SECONDS);
                    return productSku;
                } finally {
                    //释放分布式锁
                    String script = "if redis.call('get',KEYS[1]) == ARGV[1] \n" +
                            "then\n" +
                            "\treturn redis.call('del',KEYS[1]);\n" +
                            "else\n" +
                            "\treturn 0;\n" +
                            "end;";
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
                    Long result = (Long) redisTemplate.execute(redisScript, Arrays.asList(lockKey), uuid);
                    if (result == 1) {
                        log.info("释放分布式锁成功!");
                    } else {
                        log.error("释放分布式锁成功!");
                    }
                }
            } else {
                //2.2获取分布式锁失败
                log.error("获取锁失败，自旋：{}，线程名称：{}", Thread.currentThread().getId(), Thread.currentThread().getName());
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                }
                return this.getProductSku(skuId);
            }
        } catch (Exception e) {
            //e.printStackTrace();
            //兜底处理，出现异常，直接从数据库取一次数据返回。
            return this.getSkuFromDB(skuId);
        }

    }

    private ProductSku getSkuFromDB(Long skuId) {
        return productSkuMapper.selectById(skuId);
    }


    @Override
    public Product getProduct(Long id) {
        return productMapper.selectById(id);
    }


    @Override
    public SkuPrice getSkuPrice(Long skuId) {
        ProductSku productSku = productSkuMapper.selectOne(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getId, skuId).select(ProductSku::getSalePrice, ProductSku::getMarketPrice));
        SkuPrice skuPrice = new SkuPrice();
        BeanUtils.copyProperties(productSku, skuPrice);
        return skuPrice;
    }


    @Override
    public ProductDetails getProductDetails(Long id) {
        return productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
    }


    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id).select(ProductSku::getId, ProductSku::getSkuSpec));
        Map<String, Long> skuSpecValueMap = new HashMap<>();
        productSkuList.forEach(item -> {
            skuSpecValueMap.put(item.getSkuSpec(), item.getId());
        });
        return skuSpecValueMap;
    }


    @Override
    public SkuStockVo getSkuStock(Long skuId) {
        SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, skuId));
        SkuStockVo skuStockVo = new SkuStockVo();
        BeanUtils.copyProperties(skuStock, skuStockVo);
        return skuStockVo;
    }


    // select * from product_sku where id in (1,2,3)
    // select id,sale_price,market_price from product_sku where id in (1,2,3)
    @Override
    public List<SkuPrice> getSkuPriceList(List<Long> skuIdList) {
        if (CollectionUtils.isEmpty(skuIdList)) {
            throw new ServiceException("参数不能为空");
        }

        List<ProductSku> skuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getId, skuIdList));

        if (CollectionUtils.isEmpty(skuList)) {
            throw new ServiceException("数据不存在");
        }

        return skuList.stream().map(productSku -> {
            SkuPrice skuPrice = new SkuPrice();
            skuPrice.setSkuId(productSku.getId());
            skuPrice.setSalePrice(productSku.getSalePrice());
            skuPrice.setMarketPrice(productSku.getMarketPrice());
            return skuPrice;
        }).toList();
    }

    @Transactional  //要么全部锁定成功,要么全部锁定失败
    @Override
    public String checkAndLock(String orderNo, List<SkuLockVo> skuLockVoList) {

        //去重处理。锁定库存不许重复锁定。
        //分布式锁，解决去重问题。  setnx k v
        String key = "sku:checkAndLock:" + orderNo; //分布式锁的key
        String dataKey = "sku:lock:data:" + orderNo;

        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);
        if(!ifAbsent){
            if(redisTemplate.hasKey(dataKey)){
                return "";
            }else{
                return "重复提交";
            }
        }


        //检查库存
        for (SkuLockVo skuLockVo : skuLockVoList) {
            SkuStock skuStock = skuStockMapper.check(skuLockVo.getSkuId(), skuLockVo.getSkuNum()); //select查询操作
            if (skuStock == null) { //库存不够
                skuLockVo.setIsHaveStock(false);
            } else {
                skuLockVo.setIsHaveStock(true);
            }
        }

        //判断库存够不够
        if (skuLockVoList.stream().anyMatch((skuLockVo) -> !skuLockVo.getIsHaveStock())) {  //存在库存不够的商品
            List<SkuLockVo> noHaveSkuLockVoList = skuLockVoList.stream().filter((skuLockVo) -> !skuLockVo.getIsHaveStock()).toList();
            //拼串：xxx商品库存不够，把这样的串返回
            StringBuilder builder = new StringBuilder();
            for (SkuLockVo skuLockVo : noHaveSkuLockVoList) {
                builder.append(skuLockVo.getSkuId() + "- 商品库存不够;");
            }
            redisTemplate.delete(key); //删除分布式锁
            return builder.toString();
        } else { //都是库存够的情况，锁定库存
            for (SkuLockVo skuLockVo : skuLockVoList) {
                int row = skuStockMapper.lock(skuLockVo.getSkuId(), skuLockVo.getSkuNum()); //update 修改库存数量
                if (row == 0) {
                    redisTemplate.delete(key); //删除分布式锁
                    throw new ServiceException("锁定库存失败");
                }
            }
        }


        //需要将锁定库存信息保存到Redis中，便于后续业务开展：    包括 下单失败解锁库存、取消订单解锁库存、支付成功减库存 等业务。
        redisTemplate.opsForValue().set(dataKey,skuLockVoList); //不要设置失效时间，因为解锁库存和减库存业务需要这个缓存数据，并且使用完会帮我们删除。
        return ""; //空串表示锁定成功了
    }

    @Override
    public void unlock(String orderNo) {
        String key = "sku:minus:" + orderNo;//分布式锁
        String dataKey = "sku:lock:data:" + orderNo;

        Boolean isLock = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);
        if (!isLock){
            log.info("不可重复解锁");
            return;
        }

        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>)redisTemplate.opsForValue().get(dataKey);
        if (skuLockVoList.isEmpty()){
            throw new ServiceException("数据为空，无法解锁库存");
        }

        for (SkuLockVo skuLockVo : skuLockVoList) {
            int unlockNum = skuStockMapper.unlock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if (unlockNum==0){
                redisTemplate.delete(key); //解分布式锁
                throw new ServiceException("解锁库存失败");
            }

            redisTemplate.delete(dataKey);//库存解锁成功，就可以删除缓存
        }
    }


    @Override
    public void minus(String orderNo) {
        //1.去重
        String key = "sku:minus:" + orderNo;
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);
        if (!ifAbsent) {
            log.info("减库存 - 重复提交  -  去重处理 .... ");
            return;
        }
        //2.从缓存中获取 锁定库存时保存的数据
        String dataKey = "sku:lock:data:" + orderNo;
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>) redisTemplate.opsForValue().get(dataKey);
        if (CollectionUtils.isEmpty(skuLockVoList)) {
            throw new ServiceException("缓存数据为空.不能再去减库存");
        }

        //3.进行解锁
        for (SkuLockVo skuLockVo : skuLockVoList) {
            int row = skuStockMapper.minus(skuLockVo.getSkuId(), skuLockVo.getSkuNum()); //执行update语句，将锁定库存数量减掉
            if (row == 0) {
                redisTemplate.delete(key);
                throw new ServiceException("减库存失败");
            }
        }

        //4.删除缓存数据        减库存后，防止再次减库存  或  解锁库存 ;所以删除缓存
        redisTemplate.delete(dataKey);
    }
}